package com.maben.sensitive_field_search.service.impl;

import com.maben.sensitive_field_search.mapper.SysPersonMapper;
import com.maben.sensitive_field_search.pojo.SysPerson;
import com.maben.sensitive_field_search.service.SysPersonService;
import com.maben.sensitive_field_search.util.DesUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysPersonServiceImpl implements SysPersonService {

    @Resource
    private SysPersonMapper sysPersonMapper;

    /**
     * 通过手机获取人员列表
     */
    public List<SysPerson> getPersonListByPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            return new ArrayList<>();
        }
        final String encrypt = DesUtils.encrypt(phone);
        System.out.println("encrypt:" + encrypt);
        return this.sysPersonMapper.queryByPhoneEncrypt(encrypt);

    }

    /**
     * 写入人员表
     */
    public SysPerson register(SysPerson person) {
        this.sysPersonMapper.insert(person);
        String phone = DesUtils.decrypt(person.getPhone());
        String phoneKeywords = this.phoneKeywords(phone);
        this.sysPersonMapper.insertPhoneKey(person.getId(), phoneKeywords);
        return person;
    }

    /**
     * 将手机号按照默认模糊搜索长度切割（这里默认模糊搜索长度是4）
     */
    private String phoneKeywords(String phone) {
        return this.keywords(phone, 4);
    }

    /**
     * 分词组合加密（将关键字按照长度切割加密，然后拼接起来，存入表中）
     */
    private String keywords(String word, int len) {
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < word.length(); i++) {
            final int start = i;
            final int end = i + len;
            final String sub = word.substring(start, end);
            final String encrypt = DesUtils.encrypt(sub);
            System.out.println("str:" + sub + ",encrypt:" + encrypt);
            sb.append(encrypt);
            if (end == word.length()) {
                break;
            }
        }
        return sb.toString();
    }

}
